package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.oss.OssManager;
import com.cheer.ba.app.oss.UploadPicManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.MineFragItemModel;
import com.cheer.ba.presenter.impl.PersonalPresenter;
import com.cheer.ba.utils.CacheUtils;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MyListView;
import com.cheer.ba.widget.ShowPopupView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 个人信息设置
 *
 * @author HQ
 *         created at 2017/3/28 0028 9:54
 */
public class PersonalAty extends BaseCommAty implements AdapterView.OnItemClickListener, ShowPopupView.OnItemPopupClick {

    @BindView(R.id.id_personal_root)
    LinearLayout mRoot;

    //用户头像
    @BindView(R.id.id_person_head_img)
    ImageView mUserHeadImg;

    @BindView(R.id.id_personal_listv)
    MyListView myListView;

    private List<MineFragItemModel> mItems = new ArrayList<MineFragItemModel>();
    CommonAdapter<MineFragItemModel> mPersonalAdapter;

    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"拍摄", "从相册上传"};

    //记录拍照 0 拍照 1 相册
    private int mRecordIndex;
    //记录相片的绝对路径
    private String mPhotoFileName;
    private File mPhotoFile;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String path = (String) msg.obj;
                    /**
                     * 保存图片
                     */
                    ((PersonalPresenter) presenter).savePersonInfo(Session.getUserId(), IntentCode.Setting.PERSON_UP_PIC, path);
                    break;
            }
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_personal_info, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new PersonalPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.personal_info));
        ImageUtils.showCircleImg(aty, Session.getUserPicUrl(), R.drawable.ic_user_head, R.drawable.ic_user_head, mUserHeadImg);
        popupView = new ShowPopupView(this);
        popupView.setOnItemPopupClick(this);


//        MineFragItemModel item1 = new MineFragItemModel(getString(R.string.personal_head_img), 0, "", Session.getUserPicUrl(), "", false, true, true);
        MineFragItemModel item2 = new MineFragItemModel(getString(R.string.personal_name), 0, Session.getUserName(), "", "", false, true, true);
        MineFragItemModel item3 = new MineFragItemModel(getString(R.string.personal_sex), 0, Session.getUser_sex(), "", "", false, false, true);
        MineFragItemModel item4 = new MineFragItemModel(getString(R.string.personal_arear), 0, Session.getUser_area(), "", "", false, true, true);
//        MineFragItemModel item5 = new MineFragItemModel(getString(R.string.personal_signature), 0, Session.getUser_signatrue(), "", "", false, true, true);
//        MineFragItemModel item6 = new MineFragItemModel(getString(R.string.personal_desc), 0, Session.getUser_desc(), "", "", false, true, true);
//        mItems.add(item1);
        mItems.add(item2);
        mItems.add(item3);
        mItems.add(item4);
//        mItems.add(item5);
//        mItems.add(item6);
    }

    @Override
    public void initData() {
        mPersonalAdapter = new CommonAdapter<MineFragItemModel>(aty, mItems, R.layout.adp_mine_frg) {
            @Override
            public void convert(ViewHolder helper, MineFragItemModel item) {
                if (item.getDrawable() != 0) {
                    helper.getViewById(R.id.id_icon_img).setVisibility(View.VISIBLE);
                    helper.setImageResource(R.id.id_icon_img, item.getDrawable());
                } else {
                    helper.getViewById(R.id.id_icon_img).setVisibility(View.GONE);
                }
                helper.setText(R.id.id_name_txt, item.getName());
                //描述
                TextView mTxtDesc = (TextView) helper.getViewById(R.id.id_right_des_txt);
                //头像
                ImageView mHeadImg = (ImageView) helper.getViewById(R.id.id_person_head_img);
                //通知数量
                TextView mTxtNum = (TextView) helper.getViewById(R.id.id_contact_num_update);
                if (!StringUtils.isEmpty(item.getmDesc())) {
                    mTxtDesc.setVisibility(View.VISIBLE);
                    mTxtDesc.setText(item.getmDesc());
                } else {
                    mTxtDesc.setVisibility(View.GONE);
                }
                if (!StringUtils.isEmpty(item.getmHead())) {
                    mHeadImg.setVisibility(View.VISIBLE);
                    ImageUtils.showCircleImg(aty, Session.getUserPicUrl(), R.drawable.ic_user_head, R.drawable.ic_user_head, mHeadImg);
                } else {
                    mHeadImg.setVisibility(View.GONE);
                }
                if (!StringUtils.isEmpty(item.getmNum())) {
                    mTxtNum.setVisibility(View.VISIBLE);
                    mTxtNum.setText(item.getmNum());
                } else {
                    mTxtNum.setVisibility(View.GONE);
                }
                if (item.isArrow()) {
                    helper.getViewById(R.id.id_right).setVisibility(View.VISIBLE);
                } else {
                    helper.getViewById(R.id.id_right).setVisibility(View.GONE);
                }
                if (item.isDivider()) {
                    helper.getViewById(R.id.id_line_v).setVisibility(View.VISIBLE);
                    helper.getViewById(R.id.id_divider_v).setVisibility(View.GONE);
                } else {
                    helper.getViewById(R.id.id_line_v).setVisibility(View.GONE);
                    helper.getViewById(R.id.id_divider_v).setVisibility(View.VISIBLE);
                }
            }
        };
        myListView.setAdapter(mPersonalAdapter);
        myListView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            //昵称
            case 0:
                Intent name = new Intent(aty, ModifyPersonInfoAty.class);
                name.putExtra(IntentKey.Personal.KEY_MODIFY_PARAMS, getString(R.string.modify_name));
                name.putExtra(IntentKey.General.KEY_TYPE, IntentCode.Setting.PERSON_MODIFY_NAME);
                startActivityForResult(name, IntentCode.Setting.PERSON_MODIFY_NAME);
                break;
            //性别
            case 1:
                Intent sex = new Intent(aty, ModifyPersonInfoAty.class);
                sex.putExtra(IntentKey.Personal.KEY_MODIFY_PARAMS, getString(R.string.modify_sex));
                sex.putExtra(IntentKey.General.KEY_TYPE, IntentCode.Setting.PERSON_MODIFY_SEX);
                startActivityForResult(sex, IntentCode.Setting.PERSON_MODIFY_SEX);
                break;
            //地区
            case 2:
                Intent email = new Intent(aty, ProvinceAreaAty.class);
                startActivityForResult(email, IntentCode.Area.PROVINCE_REQUEST_CODE);
                break;
//            //个人签名
//            case 3:
//                break;
//            //个人简介
//            case 4:
//                break;
        }
    }

    /**
     * 头像点击
     */
    @OnClick(R.id.id_personal_head_ll)
    public void onClick() {
        popupView.showAtLocPop(mRoot, POPUP_ITEMS);
    }

    /**
     * 处理头像的信息
     */
    @Override
    public void OnItemClick(int position, String tag) {
        switch (position) {
            //拍照
            case 0:
                mRecordIndex = 0;
                checkPermissCamer();
                break;
            //系统相册
            case 1:
                mRecordIndex = 1;
                checkPermissCamer();
                break;
        }
    }

    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        if (mRecordIndex == 0) {
//            //拍照
//            perms =
//        } else {
//            //系统相册
//            perms = new String[]{};
//        }
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    /**
     * 处理拍照，系统相册
     */
    private void toPhotoGraph() {
        if (mRecordIndex == 0) {
            //拍照
            // 应该先判断SD卡是否存在
            String SDState = Environment.getExternalStorageState();
            if (SDState.equals(Environment.MEDIA_MOUNTED)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                initHeadPicPath();
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_PICTURE);// 使用手机进行拍照的请求码是：1
            } else {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_no_sd_card));
            }
        } else {
            //相册
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            /**
             * 下面这句话，与其它方式写是一样的效果，如果：
             * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             * intent.setType(""image/*");设置数据类型
             * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
             */
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_ALBUM);// 从相册中取图片的请求码是：2
        }
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            toPhotoGraph();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 已经选择了照片，这个是通过手机相机拍照返回的请求码
                case IntentCode.General.REQUEST_CODE_TAKE_PICTURE:
                    File mPhotoFile = null;
                    if (!TextUtils.isEmpty(mPhotoFileName)) {
                        mPhotoFile = new File(mPhotoFileName);
                    }
                    if (mPhotoFile != null) {
                        doPhoto(Uri.fromFile(mPhotoFile));
                    }
                    break;
                // 相册请求码
                case IntentCode.General.REQUEST_CODE_TAKE_ALBUM:
                    doPhoto(data.getData());
                    break;
                // 选择好照片后
                case IntentCode.General.CHOOSETRUE:
                    if (!TextUtils.isEmpty(mPhotoFileName)) {
                        setHeadImage(mPhotoFileName);
                    }
                    break;
                //修改昵称
                case IntentCode.Setting.PERSON_MODIFY_NAME:
                    if (null != data) {
                        String name = data.getStringExtra(IntentKey.Personal.KEY_MODIFY_PARAMS);
                        ((PersonalPresenter) presenter).savePersonInfo(Session.getUserId(), IntentCode.Setting.PERSON_MODIFY_NAME, name);
                    }
                    break;
                //修改性别
                case IntentCode.Setting.PERSON_MODIFY_SEX:
                    if (null != data) {
                        String sex = data.getStringExtra(IntentKey.Personal.KEY_MODIFY_PARAMS);
                        ((PersonalPresenter) presenter).savePersonInfo(Session.getUserId(), IntentCode.Setting.PERSON_MODIFY_SEX, sex);
                    }
                    break;
            }
        } else if (requestCode == IntentCode.Area.PROVINCE_REQUEST_CODE) {
            if (resultCode == IntentCode.Area.PROVINCE_RESULT_CODE) {
                if (null != data) {
                    String address = data.getStringExtra(IntentKey.General.KEY_DATA);
                    ((PersonalPresenter) presenter).savePersonInfo(Session.getUserId(), IntentCode.Setting.PERSON_MODIFY_ADDRESS, address);
                }
            }
        }
    }

    /**
     * 相片裁剪
     */
    private void doPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 640);
        intent.putExtra("outputY", 640);
//        intent.putExtra("return-data", true);
        intent.putExtra("return-data", false);
        initHeadPicPath();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPhotoFileName)));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, IntentCode.General.CHOOSETRUE);
    }

    private void initHeadPicPath() {
        // 创建拍摄照片保存的文件夹及图片文件名
        String imgName = StringUtils.getPhotoFileName();
        File f = new File(CacheUtils.getCacheDirectory(aty, true, "pic") + imgName);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (f != null) {
            mPhotoFileName = f.getAbsolutePath();
        }
        mPhotoFile = f;
    }

    /**
     * oss上传图片
     *
     * @param filePath
     */
    public void setHeadImage(String filePath) {
        ((PersonalPresenter) presenter).uploadPic(filePath, mUserHeadImg);
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_SUCCESS)) {
            if (null != t) {
                List<UploadPicManager.UploadInfo> resultList = (List<UploadPicManager.UploadInfo>) t;
                if (null != resultList && !resultList.isEmpty()) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = resultList.get(0).fileSavePath;
                    mHandler.sendMessage(msg);
                }
            }
        } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_FAIL)) {
            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_head_up_fail));
        }
    }

    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
        if (flag1 == CodeStatus.Gegeneral.DATA_SUCCESS_FULL) {
            modifySuccess(flag2, string);

            if (flag2 == IntentCode.Setting.PERSON_UP_PIC || flag2 == IntentCode.Setting.PERSON_MODIFY_NAME) {
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Personal.KEY_PERSONAL_UPDATE;
                EventBus.getDefault().post(event);
            }
        } else {
            switch (flag2) {
                case IntentCode.Setting.PERSON_UP_PIC:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_head_up_fail));
                    break;
                case IntentCode.Setting.PERSON_MODIFY_NAME:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_modify_name_fail));
                    break;
                case IntentCode.Setting.PERSON_MODIFY_SEX:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_modify_sex_fail));
                    break;
                case IntentCode.Setting.PERSON_MODIFY_ADDRESS:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_modify_address_fail));
                    break;
            }
        }
    }

    /**
     * 修改界面信息
     *
     * @param type
     */
    public void modifySuccess(int type, String params) {
        Log.d("huangqiang", params + "--------------");
        switch (type) {
            case IntentCode.Setting.PERSON_UP_PIC:
                Log.d("huangqiang", OssManager.OSS_HOST + params);
                Session.setUserPicUrl(Protect.setPic(params));
                ImageUtils.showCircleImg(aty, Protect.setPic(params), R.drawable.ic_user_head, R.drawable.ic_user_head, mUserHeadImg);
                break;
            case IntentCode.Setting.PERSON_MODIFY_NAME:
                Session.setUserName(params);
                MineFragItemModel mNames = mItems.get(0);
                mNames.setmDesc(params);
                mPersonalAdapter.notifyDataSetChanged();
                break;
            case IntentCode.Setting.PERSON_MODIFY_SEX:
                if (TextUtils.equals("0", params)) {
                    Session.setUser_sex("女");
                } else {
                    Session.setUser_sex("男");
                }
                MineFragItemModel mSexs = mItems.get(1);
                mSexs.setmDesc(Session.getUser_sex());
                mPersonalAdapter.notifyDataSetChanged();
                break;
            case IntentCode.Setting.PERSON_MODIFY_ADDRESS:
                Session.setUser_area(params);
                MineFragItemModel mAddress = mItems.get(2);
                mAddress.setmDesc(params);
                mPersonalAdapter.notifyDataSetChanged();
                break;
        }
    }
}